import fs from "node:fs";
import { Buffer } from "node:buffer";
import path from "node:path";

export default defineEventHandler(async (event) => {
  const body = await readFormData(event).catch(() => {
    throw createError({
      status: 406,
      message: "read body failed",
    });
  });
  // get file
  const file = body.get("file") as File | null;
  if (!file) {
    throw createError({
      status: 406,
      message: "post not a file",
    });
  }
  const fileMeta = JSON.parse(
    event.headers.get("fileMeta") ?? "{}",
  ) as FileMetaType;
  if (Reflect.ownKeys(fileMeta).length === 0) {
    throw createError({
      status: 406,
      message: "参数错误",
    });
  }
  // 分类file
  let targetDir = "misc";
  const image = /image\/\w/;
  const video = /video\/\w/;
  const fileType = fileMeta.type;
  if (image.test(fileType))
    targetDir = "image";
  else if (video.test(fileType))
    targetDir = "video";
  else targetDir = "misc";

  // 开启流
  const writableStream = fs.createWriteStream(
    path.join(process.cwd(), "public", "upload", targetDir, fileMeta.name),
  );
  // console.log('saved', targetDir)
  if (!writableStream) {
    throw createError({
      status: 503,
      message: "",
    });
  }
  // 写入流
  writableStream.write(Buffer.from(await file.arrayBuffer()));
  // 监听流的关闭事件
  writableStream.on("finish", () => {
    console.log("saved success!");
  });

  // 关闭流
  writableStream.end();
  return {
    msg: "ok",
  };
});
